package com.wxh.producerconsumer.lockprocess;

import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

/**
 * @ClassName: Resource
 * @Description: 资源
 * @Author wxh
 * @Date: 2021/12/7 14:51
 * @Version V1.0.0
 * @Since 1.8
 */
public class Resource {
    /**
     * 面包个数
     */
    private int breadCount = 0;
    /**
     * 定义一个锁对象
     */
    private Lock lock = new ReentrantLock();
    /**
     * 获得lock的生产者监视器对象
     */
    private Condition conProducer = lock.newCondition();
    /**
     * 获得lock的消费者监视器对象
     */
    private Condition conConsumer = lock.newCondition();

    /**
     *  生产资源
     */
    public void produce(){
        // 线程获取锁
        lock.lock();
        try {
            // 有资源, 生产者等待
            while (breadCount != 0){
                try {
                    conProducer.wait();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
            breadCount++;
            System.out.println(Thread.currentThread().getName() + " " + breadCount);

            // 唤醒所有消费者线程
            conConsumer.signalAll();
        }finally {
            lock.unlock();
        }
    }

    /**
     *  消费资源
     */
    public void consume(){
        lock.lock();
        try {
            // 没有资源, 消费者等待
            while (breadCount == 0){
                try {
                    conConsumer.wait();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
            breadCount--;
            System.out.println(Thread.currentThread().getName() +" "+breadCount);

            // 唤醒所有生产者线程
            conProducer.signalAll();
        }finally {
            lock.unlock();
        }
    }


}
